import {ElMessage} from "element-plus";
import {ref, computed, watchEffect, watch} from 'vue'
import { useRouter } from "vue-router";

import {defineStore} from 'pinia'
import { loginAPI, logoutAPI, registerAPI } from "../apis/user";


export const useUserStore = defineStore('user', () => {
    
  const token = ref('')
  const router = useRouter()

  const login = async(phone, password) => {
    const data = {
      phone,
      password
    }
    const res = await loginAPI(data)
    token.value = res.data
  }

  const register = async (phone, password) => {
    const data = {
      phone,
      password
    }
    const res = await registerAPI(data)
    if (res.data == null) {
      token.value = '' 
    } else {
      
      token.value = res.data
    }
    
  }

  const logout =async  () => {
    await logoutAPI()
    token.value = ''   
    router.push({path:'/'}) 
  }

    return {
     token,
     login,
     register,
     logout
    }
  },
  {
    persist: {
      key: "user",
      storage: localStorage,
      // paths:['fontSize','isGreen','isDark'],
      // paths: ["token", "loginUserInfo"],
      serializer: {
        deserialize: JSON.parse,
        serialize: JSON.stringify,
      },
    }
  }
)
